#    Copyright 2008, 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPIP.
#    COOPIP is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPIP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPIP.  If not, see <http://www.gnu.org/licenses/>.

import os
import datetime
import shutil

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopip/djangoproject/include', '/opt/coopip/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime
#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopip/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
from django.core.management import setup_environ
import djangoproject
from djangoproject import settings
setup_environ(settings)
from models import *
#********************Setup psycopg2 and django section********************

from django.template import Context, loader
from django.http import HttpResponse
from django import forms
import os
import datetime
import djangoproject.settings
import COOPIP_Misc
import djangoproject.models.ipbase
import COOPIP_Form, COOPIP_FormGeneral, COOPIP_FormRevenueProtection, COOPIP_FormIntranet, COOPIP_FormNetworkDevice
import reportlab
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import LETTER
from reportlab.lib.units import mm
from reportlab.graphics.barcode import code128
import CIS, GIS



def BuildTransformerUsageAnalysisForm():
    from django.contrib import admin
    Dict={}
    Dict['StationToPerformAnalysisOn']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'20'}))  
    Dict['DaysToDisplay']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'20'}))
    Dict['StationToUpdate']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'20'}))  
    Dict['StationTransformerUsageAnalysisComment']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'40'}))  
    Dict['CreateTransformerBankIndicator']=forms.BooleanField(required=False)
    Dict['EditTransformerBankIndicator']=forms.BooleanField(required=False)
    Dict['DeleteTransformerBankIndicator']=forms.BooleanField(required=False)
    Dict['TransformerBankDescription']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    return Dict

def ProcessTransfomerUsageAnalysisForm(form, UserName):
    import models

    import datetime
    Today=datetime.datetime.today()
    #Perform New TransformerUsageAnalysis if needed and get a list of TransformerUsageAnalysises to be displayed.
    Stationid=COOPIP_Form.FormGetInteger(form, 'StationToPerformAnalysisOn')
    DaysToDisplay=COOPIP_Form.FormGetInteger(form, 'DaysToDisplay')
    InstallStatusidForInstall=GIS.Coopgisinstallstatus.objects.filter(name='Install')[0]

    try:
        station=GIS.Coopgisstation.objects.filter(id=int(Stationid))[0]
        InstallStatusInstallid = GIS.Coopgisinstallstatus.objects.filter(name='Install')[0].id
        Transformers=GIS.Coopgisassembly.objects.filter(station=station).filter(compatibleunit__transformerindicator=True).exclude(installstatus_id=InstallStatusInstallid)
    except:
        Transformers=[]
    for transformer in Transformers:
        djangoproject.models.revenueprotection.TransformerUsageAnalysis().PerformAnalysis(transformer, Today - datetime.timedelta(days=2))
    if(DaysToDisplay):
        StartDate=Today-datetime.timedelta(days=DaysToDisplay)
    else:
        StartDate=Today-datetime.timedelta(days=1)

    if(Stationid):
        TransformerUsageAnalysises=djangoproject.models.revenueprotection.TransformerUsageAnalysis.objects.filter(CreateDateTime__gte=StartDate).filter(StationIdentifier=Stationid).order_by('AverageUtilizationPercent')
    else:
        TransformerUsageAnalysises=djangoproject.models.revenueprotection.TransformerUsageAnalysis.objects.filter(CreateDateTime__gte=StartDate).order_by('AverageUtilizationPercent')
    #End Transformer Usage Analysis/Getting A List to be displayed

    #Update Station TransformerUsageAnalysis Comment
    StationToUpdate=COOPIP_Form.FormGetObjectFromid(form, 'StationToUpdate', GIS.Coopgisstation)  
    StationTransformerUsageAnalysisComment=COOPIP_Form.FormGetString(form, 'StationTransformerUsageAnalysisComment')
    if(StationToUpdate):
        StationToUpdate.Description=StationTransformerUsageAnalysisComment
        StationToUpdate.save()
    #End Station TransformerUsageAnalysis Comment Update


    TransformerBankDescription=COOPIP_Form.FormGetString(form, 'TransformerBankDescription')
    return TransformerUsageAnalysises


def PopulateTransformerUsageAnalysisForm(form):
    form.data['StationToUpdate']=''




    form.data['StationToPerformAnalysisOn'] = ''
    form.data['StationToUpdate']=''
    form.data['StationTransformerUsageAnalysisComment']=''

    return form






